package com.stedu.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.stedu.bean.Owner;
import com.stedu.bean.RespBean;
import com.stedu.exception.SteduException;
import com.stedu.mapper.OwnerMapper;
import com.stedu.service.OwnerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/admin/owner")
public class OwnerController {
    @Autowired
    private OwnerMapper ownerMapper;
    @Autowired
    private OwnerService ownerService;
    @Value("${pageSize}")
    private Integer pageSize;
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException
    {
        System.out.println("Fetched ownerList: " );
        // 获取所有业主数据
        List<Owner> ownerList = ownerService.selectAll();

        // 打印业主列表，帮助调试
        System.out.println("Fetched ownerList: " + ownerList);

        // 设置响应内容类型为 CSV 文件
        response.setContentType("text/xlsx;charset=utf-8");
        response.setCharacterEncoding("UTF-8");

        // 设置下载文件名
        String fileName = URLEncoder.encode("业主信息", "UTF-8") + ".csv";
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

        // 构建 CSV 内容
        StringBuilder csvContent = new StringBuilder();
        csvContent.append("ID,业主姓名,业主性别,业主电话,业主头像,业主住址\n");

        for (Owner owner : ownerList) {
            csvContent.append(owner.getOid()).append(',')
                    .append(owner.getOname()).append(',')
                    .append(owner.getOgender()).append(',')
                    .append(owner.getOphone()).append(',')
                    .append(owner.getOavater()).append(',')
                    .append(owner.getOadd()).append('\n');
        }

        // 将 CSV 内容写入响应输出流
        try (ServletOutputStream out = response.getOutputStream()) {
            out.write(csvContent.toString().getBytes("UTF-8"));
        } catch (IOException e) {
            e.printStackTrace(); // 打印异常信息
        }
    }

    @PostMapping("/up")
    @Transactional  // 确保整个操作在一个事务中完成
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("文件不能为空");
        }

        try {
            // 解析CSV文件并存储数据到数据库
            List<Owner> owners = parseCSVFile(file);
            // 打印owners列表中每个Owner的信息
            for (Owner owner : owners) {
                System.out.println("Owner Name: " + owner.getOname());
                System.out.println("Gender: " + owner.getOgender());
                System.out.println("Phone: " + owner.getOphone());
                System.out.println("Avatar: " + owner.getOavater());
                System.out.println("Address: " + owner.getOadd());
                System.out.println("-----------------------------------");
            }
            ownerService.insertBatch(owners);  // 批量保存到数据库

            return ResponseEntity.ok("文件上传并导入成功，导入数据量：" + owners.size());
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件上传失败: " + e.getMessage());
        }
    }

    private List<Owner> parseCSVFile(MultipartFile file) throws Exception {
        List<Owner> owners = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8))) {
            String line;
            // 跳过表头，如果CSV文件中包含表头
            br.readLine();
            while ((line = br.readLine()) != null) {
                String[] data = line.split(",");  // 假设CSV使用逗号分隔
                if (data.length < 5) continue;  // 忽略不符合格式的行

                Owner owner = new Owner();
                owner.setOid(Integer.parseInt(data[0]));
                owner.setOname(data[1]);
                owner.setOgender(Integer.parseInt(data[2]));
                owner.setOphone(data[3]);
                // owner.setOavatar(data[3]);  // 确保avatar字段是否在CSV文件中
                owner.setOadd(data[5]);

                owners.add(owner);
            }
        }
        return owners;
    }



    @GetMapping("/selectAll")
    public RespBean selectAll()  {
        List<Owner> ownerList = ownerService.selectAll();
        return RespBean.ok("", ownerList);
    }

    @GetMapping
    public RespBean selectByPage(Integer pageNum,String oname,String ophone) throws SteduException {
        if(pageNum == null) {
            pageNum = 1;
        }

        PageHelper.startPage(pageNum, pageSize);
        List<Owner> ownerList = ownerService.selectByOname(oname,ophone);
        PageInfo<Owner> pageInfo = new PageInfo<>(ownerList);
        return RespBean.ok("查询成功", pageInfo);
    }

    @PostMapping
    public RespBean insert(@RequestBody Owner owner) throws SteduException {
        //添加
        if (ownerService.insert(owner)) {
            return RespBean.ok("添加成功~~~");
        } else {
            return RespBean.error("添加失败，请重新添加");
        }
    }
    @DeleteMapping("/{oid}")
    public RespBean delete(@PathVariable("oid") Integer oid) throws SteduException {
        if (ownerService.delete(oid)) {
            return RespBean.ok("删除成功~~~");
        } else {
            return RespBean.error("删除失败，请重新删除");
        }
    }

    @PutMapping
    public RespBean update(@RequestBody Owner owner) throws SteduException {
        if (ownerService.update(owner)) {
            return RespBean.ok("修改成功~~~");
        } else {
            return RespBean.error("修改失败，请重新修改");
        }
    }

    @GetMapping("/select/{oid}")
    public RespBean selectByOid(@PathVariable("oid") Integer oid) {
        Owner r = ownerService.selectByOid(oid);
        return RespBean.ok("", r);
    }
}
